package com.icesoft.core.web.configurer.init;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.boot.env.PropertiesPropertySourceLoader;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.IOException;

public class SimpleConfigEnvironmentPostProcessor implements EnvironmentPostProcessor {

	private static final String simplePath = "config/simple-config.properties";

	public static boolean isMockTestCase = false;
	public static boolean isTestCase = false;

	@Override
	public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
		try {
			org.springframework.boot.test.context.SpringBootTest springBootTest = application.getMainApplicationClass().getAnnotation(org.springframework.boot.test.context.SpringBootTest.class);
			if (springBootTest != null) {
				isTestCase = true;
				org.springframework.boot.test.context.SpringBootTest.WebEnvironment webEnvironment = springBootTest.webEnvironment();
				if (webEnvironment != null
						&& (org.springframework.boot.test.context.SpringBootTest.WebEnvironment.MOCK == webEnvironment
						|| org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE == webEnvironment)) {
					isMockTestCase = true;
				}
			}
		} catch (NoClassDefFoundError e) {
		}

		PropertySource<?> propertySource = load(simplePath);
		System.out.println("加载simple默认配置：" + propertySource.getSource());
		environment.getPropertySources().addLast(propertySource);
	}

	private PropertySource<?> load(String path) {
		Resource resource = new ClassPathResource(path);
		if (!resource.exists()) {
			throw new IllegalArgumentException("Resource " + path + " does not exist");
		}
		PropertiesPropertySourceLoader loader = new PropertiesPropertySourceLoader();
		try {
			return loader.load("classpath:" + path, resource).get(0);
		} catch (IOException ex) {
			throw new IllegalStateException("Failed to load yaml configuration from " + path, ex);
		}
	}
}
